package my.codeandroid.antollroid;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity {
    private final int DIALOG_SAME_SELECTION = 1;
    private final int DIALOG_NO_RESULT = 2;
    private final int DIALOG_ABOUT = 3;
    
	private Spinner startSpinner;
    private Spinner endSpinner;
    private DatabaseAdapter database;
    private Cursor plazasCursor;
    
    // Option Menu
    private final int MENU_ABOUT = 1;
    private final int MENU_FEEDBACK = 2;
    
	/*
	 * Init spinners with plazas' name.
	 * Attach event handler to button.
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        database = new DatabaseAdapter(this);
        
        startSpinner = (Spinner)findViewById(R.id.startSpinner);
        endSpinner = (Spinner)findViewById(R.id.endSpinner);
        
        plazasCursor = database.fetchAllPlazas();
        initSpinner(startSpinner);
        initSpinner(endSpinner);
        
        // Handle query button click
        Button queryButton = (Button)findViewById(R.id.queryButton);
        queryButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Validate selection
				int startId = startSpinner.getSelectedItemPosition();
				int endId = endSpinner.getSelectedItemPosition();
				if (startId == endId) {
					showDialog(DIALOG_SAME_SELECTION);
					return;
				}
				
				// Get the plaza codes for selected plazas
				plazasCursor.moveToPosition(startId);
				String startCode = plazasCursor.getString(plazasCursor.getColumnIndex(DatabaseAdapter.PLAZA_CODE));
				plazasCursor.moveToPosition(endId);
				String endCode = plazasCursor.getString(plazasCursor.getColumnIndex(DatabaseAdapter.PLAZA_CODE));
				
				// Query database
				Cursor faresCursor = database.getFares(startCode, endCode);
				if (faresCursor.getCount() == 0) {
					showDialog(DIALOG_NO_RESULT);
					return;
				}
				faresCursor.moveToNext();
				
				Intent intent = new Intent(v.getContext(), FareResultActivity.class);
				
				intent.putExtra(DatabaseAdapter.OFFPEAK_RATE, faresCursor.getFloat(faresCursor.getColumnIndex(DatabaseAdapter.OFFPEAK_RATE)));
				intent.putExtra(DatabaseAdapter.FESTIVE_RATE, faresCursor.getFloat(faresCursor.getColumnIndex(DatabaseAdapter.FESTIVE_RATE)));
				intent.putExtra(DatabaseAdapter.CLASS_1, faresCursor.getFloat(faresCursor.getColumnIndex(DatabaseAdapter.CLASS_1)));
				intent.putExtra(DatabaseAdapter.CLASS_2, faresCursor.getFloat(faresCursor.getColumnIndex(DatabaseAdapter.CLASS_2)));
				intent.putExtra(DatabaseAdapter.CLASS_3, faresCursor.getFloat(faresCursor.getColumnIndex(DatabaseAdapter.CLASS_3)));
				intent.putExtra(DatabaseAdapter.CLASS_4, faresCursor.getFloat(faresCursor.getColumnIndex(DatabaseAdapter.CLASS_4)));
				intent.putExtra(DatabaseAdapter.CLASS_5, faresCursor.getFloat(faresCursor.getColumnIndex(DatabaseAdapter.CLASS_5)));
				intent.putExtra(DatabaseAdapter.DISTANCE, faresCursor.getFloat(faresCursor.getColumnIndex(DatabaseAdapter.DISTANCE)));
				
				startActivity(intent);
			}
		});
    }
    
    /*
     * Populate spinner with Plazas' name.
     */
    private void initSpinner(Spinner spinner) {
    	SimpleCursorAdapter adapter = new SimpleCursorAdapter(
    			this, 
    			android.R.layout.simple_spinner_item, 
    			plazasCursor, 
    			new String[] {DatabaseAdapter.PLAZA_NAME}, 
    			new int[] {android.R.id.text1});
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	spinner.setAdapter(adapter);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	
    	menu.add(Menu.NONE, MENU_ABOUT, Menu.NONE, "About")
    		.setIcon(android.R.drawable.ic_menu_info_details);
    	
    	menu.add(Menu.NONE, MENU_FEEDBACK, Menu.NONE, "Feedback")
			.setIcon(android.R.drawable.ic_menu_send);
    	
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case MENU_ABOUT:
    		showDialog(DIALOG_ABOUT);
    		return true;
    	case MENU_FEEDBACK:
    		// Send email http://bit.ly/bwjtz4
    		Intent email = new Intent(Intent.ACTION_SEND);
    		email.putExtra(Intent.EXTRA_EMAIL, new String[] {"Leong Hean Hong <hong@codeandroid.my>"});
    		email.putExtra(Intent.EXTRA_SUBJECT, "Feedback For Antollroid");
    		email.setType("message/rfc822");
    		startActivity(email);
    		return true;
    	}
    	
    	return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
    	AlertDialog.Builder builder;
    	switch (id) {
    	case DIALOG_SAME_SELECTION:
    		builder = new AlertDialog.Builder(this);
    		builder.setMessage("Start and End toll plaza must be different.")
    			.setIcon(android.R.drawable.ic_dialog_alert)
    			.setPositiveButton("Ok", null);
    		return builder.create();
    		
    	case DIALOG_NO_RESULT:
    		builder = new AlertDialog.Builder(this);
    		builder.setMessage("No result found.")
    			.setIcon(android.R.drawable.ic_dialog_info)
    			.setPositiveButton("Ok", null);
    		return builder.create();
    		
    	case DIALOG_ABOUT:
    		Dialog dialog = new Dialog(this);
    		dialog.setContentView(R.layout.dialog_about);
    		dialog.setTitle("About Antollroid");
    		
    		TextView message = (TextView)dialog.findViewById(R.id.about_message);
    		// To make link clickable http://bit.ly/bdEC95
    		message.setMovementMethod(LinkMovementMethod.getInstance());
    		
    		return dialog;
    	}
    	
    	return super.onCreateDialog(id);
    }
    
    @Override
    protected void onDestroy() {
    	database.close();
    	super.onDestroy();
    }
}